<script setup lang="tsx">
defineOptions({
  name: "ELECTRICTITY_OPERATION_OVERVIEW"
});
import { ref, onMounted, computed, reactive, markRaw } from "vue";
import { useRouter } from "vue-router";
import { ArrowRightBold } from "@px-ui/icons-vue";
import fullScreen from "@/assets/svg/common/fullScreen.svg?component";
import {
  queryDeviceStatistics,
  getHandoverRecord,
  queryMainStatus,
  queryTotalElectricityStatistics,
  queryloadRateList
} from "@/api/modules/operation";
import { queryDictData } from "@/api/common";
import { useLabelLayoutBarChartFn, useLabelLayoutBarChartFn_new, useGetBarChartsAgOptions_new, useGetBarChartsAgOptions } from "@/hooks/useEcharts";
import { useRouterStoreHook } from "@/store/modules/router";
import topBoard from "@/views/common/topBoard/index.vue";
import ApprovalStatus from "@/views/common/handleover/components/ApprovalStatus.vue";
import echartsChart from "@/views/common/components/echartsChart/index.vue";
import deviceStatisticsTasks from "@/views/gas/operation/overview/components/deviceStatisticsTasks.vue";
import modelBox from "@/views/common/components/modelBox/index.vue";
import commonTable from "@/views/common/components/commonTable/index.vue";
import mainProgressStatus from "./components/mainProgressStatus.vue";
import loadRate from "./components/loadRate.vue";
import { deviceStatus_ele } from "@/utils/constant";
import { loadingTimeout } from "@/utils/http/constant";
import totalElectricityDetail from "./components/totalElectricityDetail.vue";
import ICON from "@/assets/svg/common/echarts.svg?component";

const router = useRouter();
const routerStore = useRouterStoreHook();
const { subject: classCode } = routerStore;
const height = ref<number>(234);
const shiftScrollbarHeight = computed(() => height.value - 40);

const isShowDetail = ref<boolean>(false);
const eqpRunStatusList = ref([]);

const valueIsEmpty = value => {
  if (value === "" || value == null || typeof value == "undefined") {
    return true;
  }
  return false;
};

// 市政进线状态
const mainProgressStatusRef = ref<InstanceType<typeof mainProgressStatus> | null>(null);
const mainProgressStatusData = reactive<Array<any>>([]);
const mainStatusInit = async () => {
  mainProgressStatusData.splice(0);
  const { subject: classCode } = routerStore;
  const params = { classCode };
  const res = await queryMainStatus(params, () => mainProgressStatusRef.value.loadingInstance.close());
  if (res?.length) {
    mainProgressStatusData.push(...res);
  }
};

// 总用电量统计
const totalElectricityRef = ref<InstanceType<typeof echartsChart> | null>(null);
const totalElectricityTitle = ref<string>("总用电量统计");
const totalElectricityOptions = ref<CommonEcharts.CommonEchartsOption | null>(null);
const totalElectricityInit = async () => {
  const res = await queryTotalElectricityStatistics(null, () => totalElectricityRef.value.loadingInstance.close());
  if (!res?.length) return;
  const ec = await totalElectricityRef.value.getEcharts();
  const unit = res[0].unit || "kWh";
  const xAxisData = res.map(item => item.usedDay);
  const fabData = res.map(item => item.fabUsedValue);
  const deviceData = res.map(item => item.deviceUsedValue);
  const allUsedData = res.map(item => item.allUsedValue);
  const label = {
    show: true,
    position: "top",
    formatter(params) {
      const { dataIndex = 0 } = params;
      if (typeof dataIndex !== "number") return "";
      const { allUsedValue = 0 } = res[dataIndex];
      if (typeof allUsedValue !== "number") return "";
      return allUsedValue;
    }
  };
  const legend = {
    show: true,
    right: 0
  };
  const tooltip: any = {
    trigger: "axis",
    axisPointer: {
      type: "shadow"
    }
  };
  const xAxis = [
    {
      type: "category",
      data: xAxisData
      // axisLabel: {
      //   interval: 0
      // }
    }
  ];
  const series: Array<any> = [
    {
      name: "总电量",
      type: "line",
      label: { show: true, position: "top" },
      symbol: "circle",
      symbolSize: 8,
      emphasis: { focus: "series" },
      data: allUsedData,
      itemStyle: {
        color: "#FFD360" //#FFCA45FF
      }
    },
    {
      name: "机台用电",
      type: "bar",
      stack: "Ad",
      emphasis: { focus: "series" },
      data: fabData,
      barWidth: 22,
      itemStyle: {
        color: "#4C9CFF" //#3B82F6FF
      },
      label: { show: false, position: "inside" }
    },
    {
      name: "厂务用电",
      type: "bar",
      stack: "Ad",
      emphasis: { focus: "series" },
      data: deviceData,
      barWidth: 22,
      itemStyle: {
        color: "#34D399" //#28D892
      },
      label: { show: false, position: "inside" }
    }
  ];
  const ag = { legend, tooltip, xAxis, series };
  totalElectricityOptions.value = useLabelLayoutBarChartFn_new(ec, xAxisData, fabData, totalElectricityTitle.value, unit, null, false, "top", ag);
  totalElectricityRef.value.loadingInstance.close();
};

// 负载率
const loadRateRef = ref<InstanceType<typeof loadRate> | null>(null);
const loadRateData = reactive<Array<any>>([]);
const loadRateInit = async () => {
  loadRateData.splice(0);
  const res = await queryloadRateList(null, () => loadRateRef.value.loadingInstance.close());
  if (!res?.length) return;
  loadRateData.push(...res);
};

// 交接班
const shiftTableRef = ref<InstanceType<typeof commonTable> | null>(null);
const shiftList = reactive<Array<any>>([]);
const shiftTableCloumns = ref<Array<CommonTable.TableCloumnsType>>([
  {
    label: "交接内容",
    prop: "moduleName",
    width: 100
  },
  {
    label: "责任人",
    prop: "handoverPersonNames",
    width: 100,
    render({ row }: any) {
      const { handoverPersonNames = [] } = row;
      if (handoverPersonNames?.length) {
        return () => handoverPersonNames.join(", ");
      } else {
        return () => "--";
      }
    }
  },
  {
    label: "状态",
    prop: "handoverStatus",
    width: 100,
    render({ row }: any) {
      const { handoverStatus = "" } = row;
      return () => (
        <div style={{ display: "flex", justifyContent: "center", alignItems: "center" }}>
          <ApprovalStatus status={handoverStatus || "UN_SUBMITTED"} />
        </div>
      );
    }
  }
]);
const shiftHeaderCellStyle = row => {
  const { columnIndex } = row;
  if (columnIndex === 2) {
    return {
      "text-align": "center"
    };
  } else {
    return null;
  }
};
const shiftInit = async () => {
  shiftList.splice(0);
  const { subject: className } = routerStore;
  const res = await getHandoverRecord(className, () => {
    shiftTableRef.value.loading = false;
  });
  if (res?.length) {
    shiftList.push(...res);
  }
  shiftTableRef.value.loading = false;
};
// const showTotalEleDialog = async()=>{
//   await
// }
const clickHandler = type => {
  let path = "";
  const { subject: classCode } = routerStore;
  if (type == "eqp") {
    path = "/all/equip/runManage/record";
    router.push({ path, query: { className: classCode } });
    return;
  }
  if (type == "task") {
    path = "/electricity/operation/taskView";
  }
  if (type == "alarm") {
    path = "/all/alert/business";
    router.push({ path, query: { className: classCode } });
    return;
  }
  if (type == "handover") {
    path = "/electricity/handleover/schedule";
  }
  if (type == "totalEle") {
    // showTotalEleDialog();
    isShowDetail.value = true;
  }
  if (path) {
    router.push({ path });
  }

  console.info("功能开发中，敬请期待。。。");
};

const toFullScreen = () => {
  const path = "/fullScreen/electricity/operation/overview";
  const { subject: className } = routerStore;
  const query = { className };
  const params = { path, query };
  const { href } = router.resolve(params);
  window.open(href, "_blank");
};

const initLoading = () => {
  mainProgressStatusRef.value.initLoading();
  totalElectricityRef.value.initLoading();
  loadRateRef.value.initLoading();
  shiftTableRef.value.loading = true;
};

const closeLoading = () => {
  setTimeout(() => {
    shiftTableRef.value?.loading && (shiftTableRef.value.loading = false);
  }, loadingTimeout);
};

onMounted(() => {
  initLoading();
  closeLoading();
  // 市政进线状态
  mainStatusInit().then(() => {
    mainProgressStatusRef.value.loadingInstance.close();
  });
  // 总用电量统计
  totalElectricityInit();
  // 负载率
  loadRateInit().then(() => {
    loadRateRef.value.loadingInstance.close();
  });
  // 交接班
  shiftInit();
});
</script>

<template>
  <div class="ele-overview">
    <div class="gas-overview-item all">
      <topBoard :classCode="classCode" arrow />
    </div>

    <!-- <div class="gas-overview-item one">
      <echartsChart
        ref="deviceStatisticsRef"
        arrow
        :title="deviceStatisticsTitle"
        :options="deviceStatisticsOptions"
        @btn-click="clickHandler('eqp')"
      />
    </div>
    <div class="gas-overview-item two task-item">
      <deviceStatisticsTasks
        ref="deviceStatisticsTasksRef"
        arrow
        :query-data="deviceStatisticsQueryData"
        :classCode="classCode"
        @btn-click="clickHandler('task')"
      />
    </div>
    <div class="gas-overview-item three">
      <echartsChart ref="alarmStatRef" arrow :title="alarmStatTitle" :options="alarmStatOptions" @btn-click="clickHandler('alarm')" />
    </div> -->

    <div class="gas-overview-item four">
      <modelBox title="市政进线状态">
        <mainProgressStatus ref="mainProgressStatusRef" :data="mainProgressStatusData" />
        <!-- <template #title>
          <px-button :icon="ArrowRightBold" type="info" text plain @click="clickHandler" />
        </template> -->
      </modelBox>
    </div>

    <div class="gas-overview-item five total-ele-item">
      <modelBox :title="totalElectricityTitle">
        <echartsChart ref="totalElectricityRef" :options="totalElectricityOptions" />
        <template #title>
          <component :is="markRaw(ICON)" class="chart-icon" @click="clickHandler('totalEle')" />
        </template>
      </modelBox>
      <totalElectricityDetail v-if="isShowDetail" v-model="isShowDetail" title="今日总用电量统计" />
    </div>

    <div class="gas-overview-item six">
      <modelBox title="负载率">
        <loadRate ref="loadRateRef" :data="loadRateData" />
        <!-- <template #title>
          <px-button :icon="ArrowRightBold" type="info" text plain @click="clickHandler" />
        </template> -->
      </modelBox>
    </div>

    <div class="gas-overview-item seven">
      <modelBox title="交接班">
        <commonTable
          ref="shiftTableRef"
          mode="stripe"
          :border="false"
          :pagination="false"
          :image-size="60"
          :height="shiftScrollbarHeight"
          :header-cell-style="shiftHeaderCellStyle"
          :tableCloumns="shiftTableCloumns"
          :list="shiftList"
        />
        <template #title>
          <px-button :icon="ArrowRightBold" type="primary" text plain @click="clickHandler('handover')" />
        </template>
      </modelBox>
    </div>
    <div class="full-screen">
      <fullScreen class="icon" @click="toFullScreen" />
    </div>
  </div>
</template>

<style lang="scss" scoped>
.ele-overview {
  position: relative;
  box-sizing: border-box;
  display: grid;
  grid-template-columns: repeat(24, minmax(16px, 1fr));
  // grid-auto-rows: 230px 1.15fr 1.15fr;
  grid-auto-rows: 234px 266px 265px;
  // grid-auto-rows: 4fr 5fr 5fr;
  grid-auto-flow: column dense;
  grid-gap: 16px;
  width: 100%;

  .px-icon {
    color: var(--px-color-primary);
  }

  .chart-icon {
    width: 16px;
    height: 16px;
    color: var(--px-color-primary);
    cursor: pointer;
  }

  :deep(.total-ele-item .echarts-chart) {
    padding: 0;
  }

  :deep(.task-item .px-button) {
    color: var(--px-color-primary);
  }

  .full-screen {
    position: absolute;
    top: -10px;
    right: -16px;
    display: flex;
    align-items: center;
    justify-content: center;
    width: 32px;
    height: 32px;
    cursor: pointer;
    background-color: var(--px-color-primary-light-9);
    border-radius: 4px;
    box-shadow: 0 0 4px 0 var(--px-color-primary-light-3);

    .icon {
      width: 70%;
      height: 70%;
      color: var(--px-color-primary);
    }

    &:hover {
      background-color: var(--px-color-primary-light-7);
      box-shadow: none;
    }
  }

  .gas-overview-item {
    display: flex;
    align-items: center;
    justify-content: center;

    .px-button {
      padding-right: 0;
    }
  }

  .all {
    grid-column: 1 / -1;
  }

  .one {
    grid-column: 1 / 7;
  }

  .two {
    grid-column: 7 / 21;
  }

  .three {
    grid-column: 21 / 25;
  }

  .four {
    grid-column: 1 / 19;
  }

  .five {
    grid-column: 19 / 25;
  }

  .six {
    grid-column: 1 / 19;
  }

  .seven {
    grid-column: 19 / 25;
  }

  :deep(.model-box) {
    position: relative;
  }
}
</style>
